package com.jzg.jcptadmin.ui;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.Utils.NoDoubleClick;
import com.jzg.jcptadmin.Utils.StringUtils;
import com.jzg.jcptadmin.adpter.CarGridViewPhotoAdapter;
import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.app.AppManager;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.data.local.LocalData;
import com.jzg.jcptadmin.data.vo.CarDetails;
import com.jzg.jcptadmin.data.vo.CheckPriceBean;
import com.jzg.jcptadmin.data.vo.EvaluateResultBean;
import com.jzg.jcptadmin.presenter.ReportPresenter;
import com.jzg.jcptadmin.view.FullyGridLayoutManager;
import com.jzg.jcptadmin.viewinterface.ReportInterface;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

public class PreviewReportActivity extends BaseActivity implements ReportInterface {
    @Bind(R.id.title_content)
    TextView titleContent;
    @Bind(R.id.title_return)
    ImageView titleReturn;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.tvSubtitle)
    TextView tvSubtitle;
    //订单编号
    @Bind(R.id.tvOrderNo)
    TextView tvOrderNo;
    //品牌车型
    @Bind(R.id.brandModel)
    TextView brandModel;
    //vin
    @Bind(R.id.vin)
    TextView vin;
    //服务方案
    @Bind(R.id.servicePlan)
    TextView servicePlan;
    //鉴定结果
    @Bind(R.id.appraisalResults)
    TextView appraisalResults;
    //评估师
    @Bind(R.id.appraiser)
    TextView appraiser;
    //售车价
    @Bind(R.id.salePrice)
    TextView salePrice;
    //收车价
    @Bind(R.id.buyPrice)
    TextView buyPrice;
    //品牌型号
    @Bind(R.id.makeNumber)
    TextView makeNumber;
    //发动机号
    @Bind(R.id.engineNum)
    TextView engineNum;
    //燃料
    @Bind(R.id.fuel)
    TextView fuel;
    //车辆类型
    @Bind(R.id.carType)
    TextView carType;
    //变速器
    @Bind(R.id.tranType)
    TextView tranType;
    //额定载客
    @Bind(R.id.seating)
    TextView seating;
    //使用性质
    @Bind(R.id.service)
    TextView service;
    //车身颜色
    @Bind(R.id.carColor)
    TextView carColor;
    //车牌号
    @Bind(R.id.carLicence)
    TextView carLicence;
    //注册地
    @Bind(R.id.registrationPlace)
    TextView registrationPlace;
    //厂商指导价
    @Bind(R.id.mPrice)
    TextView mPrice;
    //排量
    @Bind(R.id.exhaust)
    TextView exhaust;
    //表显里程
    @Bind(R.id.Mileage)
    TextView Mileage;
    //出厂日期
    @Bind(R.id.productionTime)
    TextView productionTime;
    //登记日期
    @Bind(R.id.RegDate)
    TextView RegDate;
    //
    @Bind(R.id.rv)
    RecyclerView rv;

    ReportPresenter reportPresenter;
    private Map<String, String> submitParams;
    private String brandModelData, serviceData, carColorData, area_contentData, cartypeData;

    List<CarDetails.CarPicListEntity> CarPicList;
    public CarDetails details;
    private FullyGridLayoutManager gridLayoutManager;
    private CarGridViewPhotoAdapter adapter;
    private NoDoubleClick noDoubleClick;//防止重复提交

    private CountDownTimer timer = new CountDownTimer(10000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvRight.setText("提交" + "(" + millisUntilFinished / 1000 + "S)");
        }

        @Override
        public void onFinish() {
            tvRight.setEnabled(true);
            tvRight.setClickable(true);
            tvRight.setText("提交");
            timer.cancel();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview_report);
        ButterKnife.bind(this);
        noDoubleClick = new NoDoubleClick();
        initView();
        submitParams = (HashMap) getIntent().getSerializableExtra("submitParams");
        brandModelData = getIntent().getStringExtra("brandModel");
        serviceData = getIntent().getStringExtra("service");
        carColorData = getIntent().getStringExtra("carColor");
        area_contentData = getIntent().getStringExtra("area_content");
        cartypeData = getIntent().getStringExtra("cartype");
        details = getIntent().getParcelableExtra("details");
        CarPicList = details.getCarPicList();

        reportPresenter = new ReportPresenter();
        reportPresenter.attachView(this);
        showData();
        timer.start();
        tvRight.setEnabled(false);
        tvRight.setClickable(false);
    }

    private void showData() {
        //订单编号
        tvOrderNo.setText("NO." + details.getOrderNo());
        //品牌车型
        brandModel.setText(brandModelData);
        //vin
        vin.setText(submitParams.get("VIN"));
        //服务方案
        servicePlan.setText("线上鉴定估值");
        //鉴定结果
        appraisalResults.setText(submitParams.get("appraisedes"));
        //评估师
        appraiser.setText(AppContext.getContext().getUser().getNickName());
        //售车价
        salePrice.setText(StringUtils.DoubleToString(submitParams.get("SalePrice")) + "万");
        //收车价
        buyPrice.setText(StringUtils.DoubleToString(submitParams.get("appraiseprice")) + "万");
        //品牌型号
        makeNumber.setText(submitParams.get("makeNumber"));
        //发动机号
        engineNum.setText(submitParams.get("engineNum"));
        //燃料
        fuel.setText(submitParams.get("fuel"));
        //车辆类型
        carType.setText(cartypeData);
        //变速器
        tranType.setText(submitParams.get("tranType"));
        //额定载客
        seating.setText(submitParams.get("seating"));
        //使用性质
        service.setText(serviceData);
        //车身颜色
        carColor.setText(carColorData);
        //车牌号
        carLicence.setText(submitParams.get("carLicence"));
        //注册地
        registrationPlace.setText(area_contentData);
        //厂商指导价
        mPrice.setText(submitParams.get("mPrice") + "万元");
        //排量
        exhaust.setText(submitParams.get("exhaust") + "L");
        //表显里程
        Mileage.setText(StringUtils.DoubleToString(submitParams.get("Mileage"), 10000) + "万公里");
        //出厂日期
        productionTime.setText(StringUtils.formatData(submitParams.get("productionTime")));
        //登记日期
        RegDate.setText(StringUtils.formatData(submitParams.get("RegDate")));

        gridLayoutManager = new FullyGridLayoutManager(this, 2);
        gridLayoutManager.setScrollEnabled(false);
        rv.setLayoutManager(gridLayoutManager);
        adapter = new CarGridViewPhotoAdapter((AppContext) this.getApplicationContext(), CarPicList);
        rv.setAdapter(adapter);
    }

    private void initView() {
        titleContent.setText("精真估车辆鉴定书");
        tvRight.setText("提交");
    }


    @OnClick({R.id.title_return, R.id.tv_right})
    public void onClick(View view) {
        if (!noDoubleClick.canClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.title_return:
                finish();
                break;
            case R.id.tv_right:
                checkPrice();
                break;
        }
    }

    private void checkPrice() {
        showDialog();
        Map<String, String> params = new HashMap<>();
        params.put("taskID", submitParams.get("taskid"));
        params.put("mileage", submitParams.get("Mileage"));
        params.put("userID", appContext.getUser().getUserId() + "");
        params.put("styleID", submitParams.get("StyleId"));
        params.put("RecordDate", submitParams.get("RegDate"));
        params.put("recordCityID", submitParams.get("CityId"));
        params.put("recordProvID", details.getProvinceId());
        //售车价（万元）
        params.put("salePrice", submitParams.get("SalePrice"));
        //收车价（万元）
        params.put("assessmentPrice", submitParams.get("appraiseprice"));
        Map<String, Object> maps = new HashMap<>();
        maps.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(maps));
        reportPresenter.checkPrice(params);
    }

    @Override
    public void checkPriceSuccess(CheckPriceBean priceBean) {
        dismissDialog();
        if (priceBean.status == 100) {
            //1 ：合理估值
            if (priceBean.Data.Code == 1) {
                showDialog();
                reportPresenter.OperationEvaluationData(submitParams);
            } else if (priceBean.Data.Code == 2 || priceBean.Data.Code == 3) {
                // 2 ：超过预警值  3 ：超过峰值，但未超出评估次数
                String msg = priceBean.Data.Message + "\r\n问题价格：" + priceBean.Data.Price;
                String confirmText = priceBean.Data.Code == 2 ? "确认价格提交" : "确认价格";
                String cancelText = priceBean.Data.Code == 2 ? "修改价格" : "修改价格(1)";
                SweetAlertDialog sweetDialog = new SweetAlertDialog(this);
                SweetAlertDialog.OnSweetClickListener confirmListener = new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        showDialog();
                        reportPresenter.OperationEvaluationData(submitParams);
                    }
                };
                SweetAlertDialog.OnSweetClickListener cancelListener = new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        finish();
                    }
                };
                sweetDialog.setContentText(msg);
                sweetDialog.setConfirmText(confirmText);
                sweetDialog.setConfirmClickListener(confirmListener);
                sweetDialog.setCancelText(cancelText);
                sweetDialog.setCancelClickListener(cancelListener);
                sweetDialog.show();
            }
        } else {
            MyToast.showLong(priceBean.msg);
        }
    }

    @Override
    public void evaluationSuccess(EvaluateResultBean successData) {
        dismissDialog();
        if (successData.status == 100) {
            //  1 ：合理估值    2 ：超过预警值
            if (successData.Data.Code == 1) {
                MyToast.showShort("成功提交评估信息");
                closeEvaluateActivity();
            } else {
                final SweetAlertDialog sweetDialog = new SweetAlertDialog(this);
                sweetDialog.setConfirmText("知道了");
                sweetDialog.setContentText(successData.Data.Message);
                sweetDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetDialog.dismiss();
                        closeEvaluateActivity();
                    }
                });
                sweetDialog.show();
            }
        } else {
            MyToast.showLong(successData.msg);
        }
    }

    private void closeEvaluateActivity() {
        LocalData.isRefresh = true;
        finish();
        AppManager.getAppManager().finishActivity(EvaluationActivity.class);
        AppManager.getAppManager().finishActivity(FastOnlineCheckActivity1.class);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        reportPresenter.detachView();
    }
}
